package com.project_doctor.websocket;

// src/main/java/com/example/chatsystem/netty/WebSocketServer.java


import com.project_doctor.handler.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

@Component
// 改为单例模式，确保Spring正确管理生命周期
public class WebSocketServer {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    @Value("${netty.websocket.port}")
    private int port;

    @Value("${netty.websocket.path}")
    private String path;

    @Autowired
    private WebSocketHandler webSocketHandler;

    @Autowired
    private ApplicationContext applicationContext;

    private EventLoopGroup bossGroup = new NioEventLoopGroup();
    private EventLoopGroup workerGroup = new NioEventLoopGroup();

    // 心跳超时时间：读超时60秒，写超时30秒
    private static final int READ_TIMEOUT = 60;
    private static final int WRITE_TIMEOUT = 30;

    @PostConstruct
    public void start() throws Exception {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();

                        // HTTP编解码器
                        pipeline.addLast(new HttpServerCodec());
                        pipeline.addLast(new HttpObjectAggregator(65536));

                        // 心跳检测
                        pipeline.addLast(new IdleStateHandler(READ_TIMEOUT, WRITE_TIMEOUT, 0, TimeUnit.SECONDS));

                        // WebSocket协议处理器
                        pipeline.addLast(new WebSocketServerProtocolHandler(path, null, true));

                        // 自定义WebSocket处理器（从Spring上下文获取，确保依赖注入）
                        pipeline.addLast(applicationContext.getBean(WebSocketHandler.class));
                    }
                });

        Channel channel = bootstrap.bind(port).sync().channel();
        logger.info("WebSocket服务器启动，端口: {}, 路径: {}", port, path);
    }

    @PreDestroy
    public void shutdown() {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        logger.info("WebSocket服务器已关闭");
    }
}